import React, { useState, useRef, useEffect } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Upload,
  message,
  Modal,
} from 'antd';
import { Link } from 'react-router-dom';
import Channel from 'components/Channel';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss'; //样式当js引入
import { Radio } from 'antd';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';
import {
  addArticleByIdAPI,
  getArticleByIdAPI,
  editAritcleByIdAPI,
} from 'api/article';
export default function ArticlePublish(myprops) {
  // 转变为受控组件,数据的双向绑定，监控数组里面的随时变化
  const [type, setType] = useState(1); //保留图选中状态
  const [imgView, setImgView] = useState('');
  const [fileList, setFileList] = useState([]);
  const draftRef = useRef(false);
  const formtRef = useRef({});

  const articleId = myprops.match.params.id;
  const props = {
    name: 'image',
    accept: '.png,.jpg', //浏览器打开窗口右下角有格式限定
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`, 1);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`, 1);
      }
    },
    onPreview(file) {
      // 预览
      setImgView(file.thumbUrl || file.url);
    },
    // 限制上传图片类型
    beforeUpload(file) {
      //  白名单
      let whiteImg = ['image/png', 'image/jpg'];
      if (!whiteImg.includes(file.type)) {
        message.warning('请选择正确的图片格式');
        return Upload.LIST_IGNORE;
      }
    },
  };

  const handleFinish = async (values) => {
    // 点击上传

    let fromDate = { ...values };
    fromDate.cover = {
      type: values.type,
      images: fileList.map((item) =>
        item.response ? item.response.data.url : item.url
      ),
    };
    delete fromDate.type;
    if (articleId) {
      await editAritcleByIdAPI(articleId, fromDate, draftRef.current);
      message.success('编辑成功');
    } else {
      await addArticleByIdAPI(fromDate, draftRef.current);
      message.success('上传成功');
    }

    myprops.history.push('/list');
  };
  // handleValuesChange,表单一输入就有内容打印
  const handleValuesChange = (changedValues, allValue) => {
    // 2.1 判断changedValues有type这个属性，且不为undefined的时候，setState更新type

    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };
  // 计算属性过滤数组
  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });

  // 有id会显数据

  const getArticleFn = async (id) => {
    const res = await getArticleByIdAPI(id);
    formtRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });
    setType(res.data.cover.type);
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  };
  useEffect(() => {
    if (articleId) {
      getArticleFn(articleId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <div style={{ padding: 10 }} className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{articleId ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formtRef}
          size="large"
          name="basic"
          autoComplete="off"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={handleFinish}
          initialValues={{
            content: '',
            type: 1, //给表单默认值
            title: '哈哈',
          }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入文章标题',
              },
            ]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择频道',
              },
            ]}
          >
            <Channel allowClear></Channel>
          </Form.Item>
          {/* required: true,必填就会有小小星星 */}
          <Form.Item
            label="文本域"
            name="content"
            rules={[
              {
                massage: '输入的内容不能为空',
                validator: (_, value) => {
                  console.log(value);
                  if (!value || value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  // 通过
                  return Promise.resolve();
                },
              },
              {
                required: true,
              },
            ]}
          >
            <ReactQuill
              theme="snow"
              placeholder="请输入文章内容..."
            ></ReactQuill>
          </Form.Item>
          {/* 上传图片 */}
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 图片 */}
          <Form.Item name="cover" wrapperCol={{ offset: 4 }}>
            <Upload listType="picture-card" {...props} fileList={showFileList}>
              {fileList.length < type && <UploadOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {articleId ? '编辑' : '发布'}文章
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        title="预览图片"
        visible={!!imgView}
        footer={null}
        onCancel={() => setImgView('')}
        style={{ textAlign: 'center' }}
      >
        <img
          src={imgView}
          alt=""
          width={370}
          style={{ objectFit: 'cover' }}
        ></img>
      </Modal>
    </div>
  );
}
